package com.hngy.xpq.sharedpreferencesdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private SharedPreferences info;
    private EditText name, key;
    private Button login, read;
    private CheckBox storage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化数据
        init();
        // 注册触发事件
        onclick();
    }

    private void init() {
        // EditText
        name = findViewById(R.id.name);
        key = findViewById(R.id.key);
        // Button
        login = findViewById(R.id.login);
        read = findViewById(R.id.read);
        // storage
        storage = findViewById(R.id.storage);
        // 绑定 SharedPreferences 文件
        info = super.getSharedPreferences("info", MODE_PRIVATE);
        // 如果保存了密码，覆盖 EditText
        if (info.getString("storage","").length() == 4) {
            name.setText(info.getString("name",""));
            key.setText(info.getString("key",""));
            storage.setChecked(true);
        }
    }

    private void onclick() {
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 存储数据
                storageInfo();
                Log.i("storage", String.valueOf(storage.isChecked()));
            }
        });
        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 读取数据
                readInfo();
            }
        });
    }

    private void storageInfo() {
        // ...其实密码不应该保留在SharedPreferences里的，最好保留加了密的key
        SharedPreferences.Editor editor = info.edit();  // 开始
        editor.putString("name", name.getText().toString());
        editor.putString("key", key.getText().toString());
        editor.putString("storage", String.valueOf(storage.isChecked()));
        editor.commit();  // 结束
        Toast.makeText(this, "存储成功!", Toast.LENGTH_SHORT).show();
    }

    private void readInfo() {
        // ...读取数据如何处理，比如：登录前需要记住密码
        Log.i("data-name:", info.getString("name", ""));
        Log.i("data-key:", info.getString("key", ""));
        name.setText(info.getString("name", ""));
        key.setText(info.getString("key", ""));
    }
}